package com.example.chapter06;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.database.LoginDBHelper;
import com.example.chapter06.entity.PhoneAndPassword;
import com.example.chapter06.util.ToastUtil;
import com.example.chapter06.util.ViewUtil;

public class LoginSQLiteActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener {

    private EditText et_password;
    private CheckBox ck_remember;

    private EditText et_phone;

    private SharedPreferences phone_password_info;
    private LoginDBHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_sqlite);

        ck_remember = findViewById(R.id.ck_remember);
        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);

        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_register).setOnClickListener(this);

        //给et_phone添加文本变更监听器
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone, 11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password, 6));

        et_password.setOnFocusChangeListener(this);

        phone_password_info = getSharedPreferences("phone_password_info", Context.MODE_PRIVATE);


    }

    //最后一次登录的显示到刚打开的页面
    private void reload() {
        /*
        *boolean isRemember = phone_password_info.getInt("remember",-1) == 1;
        if(isRemember){
            et_phone.setText(phone_password_info.getString("phone",null));
            et_password.setText(phone_password_info.getString("password",null));
            ck_remember.setChecked(true);
        }*/

        PhoneAndPassword pap = mHelper.queryTop();
        if (pap != null) {
            et_phone.setText(pap.getPhone());
            et_password.setText(pap.getPassword());
            ck_remember.setChecked(true);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mHelper = LoginDBHelper.getInstance(this);
        mHelper.openReadLink();
        mHelper.openWriteLink();

        reload();
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHelper.closeLink();

    }

    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        String password = et_password.getText().toString();
        if (v.getId() == R.id.btn_register) {
            Intent intent = new Intent(this, registerActivity.class);
            startActivity(intent);
        }
        //点击了登录按钮
        if (v.getId() == R.id.btn_login) {
            //查数据库是否存在该手机号码
            if (!mHelper.isExistPhone(phone)) {
                Toast.makeText(this, "当前手机号码不存在，请先注册", Toast.LENGTH_SHORT).show();
                return;
            }
            //密码是否正确
            PhoneAndPassword pap = new PhoneAndPassword();
            pap.setPhone(phone);
            pap.setPassword(password);
            pap.setRemember(ck_remember.isChecked() ? 1 : 0);
            Log.d("liu", pap.getRemember() + "");
            if (!mHelper.isExist(pap)) {
                ToastUtil.show(this, "密码输入错误，请重新输入");
                return;
            }

            //手机号存在，密码正确
            //更新数据库
            mHelper.update(pap);
            //点击了记住密码
            if (ck_remember.isChecked()) {
                SharedPreferences.Editor editor = phone_password_info.edit();
                editor.putString("phone", phone);
                editor.putString("password", password);
                editor.putInt("remember", ck_remember.isChecked() ? 1 : 0);
                editor.apply();
            }
            loginSuccess();

        }
    }

    private void loginSuccess() {
        String desc = String.format("当前手机号为：%s,密码为：%s", et_phone.getText().toString(),
                et_password.getText().toString());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登陆成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确认返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("我再看看", null);
        builder.create().show();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.et_password && hasFocus) {
            PhoneAndPassword pap = mHelper.queryByPhone(et_phone.getText().toString());
            if (pap != null) {
                et_password.setText(pap.getPassword());
            }
        }
    }

    private class HideTextWatcher implements TextWatcher {
        private final EditText mView;
        private final int maxLength;

        public HideTextWatcher(EditText et, int maxLength) {
            this.maxLength = maxLength;
            this.mView = et;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == maxLength) {
                ViewUtil.hideOneInputMethod(LoginSQLiteActivity.this, mView);
            }
        }
    }
}